<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem" />
  </div>
  <el-dialog v-model="addOrUpdateVisible" :title="title" :before-close="handleClose">
    <div>
      <el-form ref="entRef" label-width="140px" :model="form" :rules="rules" :disabled="isView">
        <el-form-item label="企业名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入企业名称" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="社会统一信用代码" prop="socialCode">
          <el-input v-model="form.socialCode" :maxlength="18" placeholder="请输入社会统一信用代码" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input v-model="form.contactPhone" :maxlength="11" placeholder="请输入联系方式" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入企业地址" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 3, maxRows: 5 }"
            :maxlength="1000" :show-word-limit="true"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!isView" @click="addOrUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm"> 确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="entUserVisible" title="企业账号信息" :before-close="handleClose">
    <div style="display: flex;justify-content: center;align-items: center">
      <span id="div-to-copy" style="cursor: pointer" @click="handleCopy(entUserName || '', entUserPsw || '')">
        <span style="padding: 0 20px 0 0 ">企业账号：<span style="color: #409EFF">{{ entUserName }}</span></span>
        <span style="padding: 0 0 0 20px ">企业密码：<span style="color: #409EFF">{{ entUserPsw }}</span></span>
      </span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="entUserVisible = false"> 确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import tablePaging from '@/views/common/component/table-paging'
import { onMounted, reactive, ref } from 'vue'
import {
  tableItem,
  operationItem,
  entEditApi, entAddApi, entViewPasswordApi, orgListApi
} from './const.js'
import { ElMessage } from 'element-plus'
import { orgAddApi, orgChangeStatusApi, orgEditApi, orgInfoApi } from '../org/const'
import { validateCreditCode } from '../../../../utils/validate'
import { clearForm } from '../../../../utils'
const { proxy } = getCurrentInstance();
const title = ref('');
const isAdd = ref(false);
const isView = ref(false);
const addOrUpdateVisible = ref(false);
const entUserVisible = ref(false);
const entRef = ref('')
const entUserName = ref('')
const entUserPsw = ref('')
const handleClose = () => {
  reset();
  addOrUpdateVisible.value = false;
  entUserVisible.value = false;
};
const form = reactive({
  userId: '',
  nickName: '',
  socialCode: '',
  contactName: '',
  contactPhone: '',
  address: '',
  remark: '',
  defaultFlag: '',
  postIds: [],
  roleIds: []
},)
const rules = reactive({
  nickName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  socialCode: [{ required: true, validator: validateCreditCode, trigger: 'blur' }],
  contactPhone: [{ required: false, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
})
// // 日期处理
// operationItem.SearchItem[2].handle = () => {
//   clickSearch()
// }

// 搜索
operationItem.menuArray[0].handle = () => {
  clickSearch()
}

// 新增
operationItem.menuArray[1].handle = () => {
  clickAdd()
}
//查看
tableItem.btnArray[0].handle = (row) => {
  clickViewOrEdit('view', row)
}
//修改
tableItem.btnArray[1].handle = (row) => {
  clickViewOrEdit('edit', row)
}
//查看密码
tableItem.btnArray[2].handle = (row) => {
  clickViewPsw(row)
}
//禁用
tableItem.btnArray[3].handle = (row) => {
  clickChangeStatus(row)
}
//启用
tableItem.btnArray[4].handle = (row) => {
  clickChangeStatus(row)
}

function setOptionsList() {
  let dataRequest = {
    nickName: '',
    typeCodeList: []
  }
  orgListApi(dataRequest).then(res => {
    const orgList = res.rows || res.data
    let enterpriseSet = new Set()
    let institutionSet = new Set()
    operationItem.SearchItem[0].options.length = 0;
    operationItem.SearchItem[1].options.length = 0;
    orgList.map(item => {
      if (item.typeCode === 'enterprise') {
        if (!enterpriseSet.has(item.nickName)) { //过滤去重
          enterpriseSet.add(item.nickName)
          operationItem.SearchItem[0].options.push({ label: item.nickName, value: item.nickName })
        }

      }
      if (item.typeCode === 'institution' || item.typeCode === 'association') {
        if (!institutionSet.has(item.nickName)) {
          institutionSet.add(item.nickName)
          operationItem.SearchItem[1].options.push({ label: item.nickName, value: item.nickName })
        }
      }
    })
  })
}

function clickSearch() {
  tableItem.pageInfo.paging()
}

function clickAdd() {
  reset();
  addOrUpdateVisible.value = true;
  title.value = "新增企业";
  isAdd.value = true
  isView.value = false
}
function clickViewOrEdit(type, row) {
  addOrUpdateVisible.value = true;
  isAdd.value = false
  proxy.resetForm("entRef");
  if (type === 'view') {
    title.value = "企业信息";
    isView.value = true
  }
  if (type === 'edit') {
    title.value = "修改企业";
    isView.value = false
  }
  orgInfoApi(row.userId).then(res => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
    form.postIds = res.postIds
    form.roleIds = res.roleIds
  });
}

//提交表单
function submitForm() {
  if (!isView.value) {
    proxy.$refs["entRef"].validate(valid => {
      if (valid) {
        if (isAdd.value) {
          entAddApi(form).then(res => {
            if (res.code === 200 && (res.data || res.rows)) {
              let data = res.data || res.rows
              entUserName.value = data.userName
              entUserPsw.value = data.rePassword
              addOrUpdateVisible.value = false;
              entUserVisible.value = true
              tableItem.pageInfo.paging()
              ElMessage.success('新增成功');
            }
          })
        } else {
          entEditApi(form).then(res => {
            addOrUpdateVisible.value = false;
            tableItem.pageInfo.paging()
            ElMessage.success('修改成功');
          })
        }
      }
    })
  } else {
    addOrUpdateVisible.value = false;
  }
}

//查看密码
function clickViewPsw(row) {
  entUserVisible.value = true
  entViewPasswordApi({ userId: row.userId }).then(res => {
    entUserName.value = row.userName
    entUserPsw.value = res.msg
  })
}
//复制操作
function handleCopy(label, password) {
  // 创建一个临时的文本输入框元素
  const input = document.createElement('textarea');
  input.value = '企业账号:' + label + '企业密码:' + password;
  document.body.appendChild(input);
  // 选择并复制文本
  input.select();
  document.execCommand('copy');
  // 清理临时元素
  document.body.removeChild(input);
  ElMessage.success('账号密码复制成功！');

}

//禁用/启用
function clickChangeStatus(row) {
  let text = row.status === "0" ? "禁用" : "启用";
  proxy.$modal.confirm('确认要' + text + '【' + row.nickName + '】用户吗?').then(function () {
    let dataRequest = {
      userId: row.userId,
      status: row.status === '0' ? '1' : '0'
    }
    return orgChangeStatusApi(dataRequest);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    tableItem.pageInfo.paging()
  }).catch(() => { });
}

function reset() {
  clearForm(form)
  form.postIds = []
  form.roleIds = []
  proxy.resetForm("entRef");
}

onMounted(() => {
  setOptionsList()
  const getUserInfo = JSON.parse(localStorage.getItem('userInfo'))
  console.log(getUserInfo,'getUserInfo')
  if (getUserInfo) {
    // 机构institution 协会association 企业enterprise
    //企业不显示机构
    if (getUserInfo.typeCode != 'admin') {
      tableItem.column[1].width=0
      operationItem.SearchItem[1].type = '9999'
    }
  }
})
</script>

<style></style>
